import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

class MessageJson{
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "MessageJson{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

@WebServlet("/message")
public class ExpressServlet extends HttpServlet {
    private ObjectMapper objectMapper=new ObjectMapper();
    //private List<MessageJson> messageJsonList=new ArrayList<>();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //客户端提交以后将数据发送给服务器,将请求中的json数据解析到Message对象中
        MessageJson messageJson=objectMapper.readValue(req.getInputStream(),MessageJson.class);
        //messageJsonList.add(messageJson);
        System.out.println(messageJson.toString());
        save(messageJson);
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write("{ \"ok\": 1 }");
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //客户端从服务器获取数据
       resp.setContentType("application/json;charset=utf8");
        List<MessageJson> messageJsonList=load();
        //将对象的List解析为json格式字符串并返回给客户端
        String respString=objectMapper.writeValueAsString(messageJsonList);
        resp.getWriter().write(respString);
    }

    /**
     * 保存message数据到服务器
     * @param messageJson
     */
    private void save(MessageJson messageJson)  {
        //1.建立连接
        Connection connection= null;
        PreparedStatement preparedStatement=null;
        try {
            connection = DBUtil.getConnection();
            //2.sql语句处理
            String sql="insert into message values(?,?,?)";
            //3.创建sql语句的对象,设置好参数
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setString(1,messageJson.from);
            preparedStatement.setString(2,messageJson.to);
            preparedStatement.setString(3,messageJson.message);
            //4.提交
            int result=preparedStatement.executeUpdate();
            if(result==1){
                System.out.println("提交成功");
            }else{
                System.out.println("提交失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection, preparedStatement, null);
        }
    }

    /**
     * 读取message数据
     * @return
     */
    private List<MessageJson> load() {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        List<MessageJson> messageJsonList=new ArrayList<>();
            try {
                connection=DBUtil.getConnection();
                String sql="select * from message";
                preparedStatement=connection.prepareStatement(sql);
                resultSet=preparedStatement.executeQuery();
                while (resultSet.next()){
                    MessageJson messageJson=new MessageJson();
                    messageJson.from=resultSet.getString("from");
                    messageJson.to=resultSet.getString("to");
                    messageJson.message=resultSet.getString("message");
                    messageJsonList.add(messageJson);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                DBUtil.close(connection,preparedStatement,resultSet);
            }
            return messageJsonList;
    }
}
